from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
from xml.dom import minidom
from BeautifulSoup import BeautifulSoup

import re
import urllib2
import Query

def OnBlipSubmitted(properties, context):
    blip = context.GetBlipById(properties['blipId'])
    query = re.match('\[(.+)\]', blip.GetDocument().GetText()).group(1)
    
    dom = minidom.parse(urllib2.urlopen("http://api.bit.ly/shorten?version=2.0.1&longUrl=http://www.wolframalpha.com/input/?i="+urllib2.quote(query)+"&login=gmaster1440&format=xml&apiKey=R_8f6af83ca44038ae7513d3d7be4a017a"))
    bitly_url = str(dom.getElementsByTagName("shortUrl")[0].firstChild.data)
    
    soup = BeautifulSoup(urllib2.urlopen('http://www.wolframalpha.com/input/?i='+urllib2.quote(query)))
    result_list = soup.findAll(id=re.compile("scannerresult"))
    
    Query.AddQuery(query,result_list)
               
    if not result_list:
	sub_blip = blip.CreateChild()
        sub_blip.GetDocument().AppendText("No result exists. Try: %s" % bitly_url)
    else:
	sub_blip = blip.CreateChild()
        for i in result_list:
            sub_blip.GetDocument().AppendText("\n")
            image = document.Image(i.img['src'])
            sub_blip.GetDocument().AppendElement(image)
        sub_blip.GetDocument().AppendText("\n"+bitly_url)

def OnRobotAdded(properties, context):
    context.GetRootWavelet().CreateBlip().GetDocument().SetText("\nPlace query in [  ]\n\nVisit http://wave-alpha.appspot.com/ to monitor live WaveAlpha requests.")

if __name__ == '__main__':
  myRobot = robot.Robot('WaveAlpha',
      image_url='http://www.wave-alpha.appspot.com/assets/icon.png',
      version='2',
      profile_url='http://www.code.google.com/p/wavealpha')
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.Run()
